const http = require('http');

const API_BASE = 'http://localhost:5000/api';

function makeRequest(url, options = {}) {
  return new Promise((resolve, reject) => {
    const requestOptions = {
      method: options.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      }
    };

    const req = http.request(url, requestOptions, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve({
            status: res.statusCode,
            data: jsonData
          });
        } catch (e) {
          resolve({
            status: res.statusCode,
            data: data
          });
        }
      });
    });

    req.on('error', (error) => {
      console.error('请求错误:', error.message);
      reject(error);
    });
    
    if (options.body) {
      req.write(options.body);
    }
    
    req.end();
  });
}

async function testEnhancedAISuggestions() {
  console.log('🧠 测试增强AI建议系统...\n');

  try {
    // 1. 测试用户统计API
    console.log('1️⃣ 测试用户统计API...');
    const statsResponse = await makeRequest(`${API_BASE}/ai/user-stats/default_user?days=30`);
    
    if (statsResponse.status === 200) {
      console.log('   ✅ 用户统计获取成功');
      console.log('   📊 统计数据:');
      const stats = statsResponse.data.stats;
      console.log(`      - 总任务数: ${stats.totalTasks}`);
      console.log(`      - 完成任务数: ${stats.completedTasks}`);
      console.log(`      - 完成率: ${stats.completionRate.toFixed(1)}%`);
      console.log(`      - 平均每日任务数: ${stats.averageTasksPerDay.toFixed(1)}`);
      console.log(`      - 最活跃时间: ${stats.mostActiveHour}:00`);
      console.log(`      - 常用分类: ${stats.mostUsedCategory}`);
      console.log(`      - 常用优先级: ${stats.mostUsedPriority}`);
    } else {
      console.log(`   ❌ 用户统计获取失败: ${JSON.stringify(statsResponse.data)}`);
    }

    // 2. 测试个性化建议API（增强版）
    console.log('\n2️⃣ 测试增强版个性化建议...');
    const suggestionsResponse = await makeRequest(`${API_BASE}/ai/personalized-suggestions`, {
      method: 'POST',
      body: JSON.stringify({
        userId: 'default_user',
        context: '用户希望提高工作效率，当前有多个紧急任务需要处理'
      })
    });

    if (suggestionsResponse.status === 200) {
      console.log('   ✅ 个性化建议生成成功');
      console.log('   🎯 建议列表:');
      const suggestions = suggestionsResponse.data.suggestions || [];
      suggestions.forEach((suggestion, index) => {
        console.log(`      ${index + 1}. [${suggestion.type}] ${suggestion.message}`);
        if (suggestion.personalizedScore) {
          console.log(`         个性化评分: ${(suggestion.personalizedScore * 100).toFixed(1)}%`);
        }
        if (suggestion.reasoning) {
          console.log(`         建议原因: ${suggestion.reasoning}`);
        }
        if (suggestion.actions && suggestion.actions.length > 0) {
          console.log(`         可执行操作: ${suggestion.actions.map(a => a.label).join(', ')}`);
        }
        console.log('');
      });
    } else {
      console.log(`   ❌ 个性化建议生成失败: ${JSON.stringify(suggestionsResponse.data)}`);
    }

    // 3. 测试建议反馈API
    console.log('3️⃣ 测试建议反馈功能...');
    const feedbackResponse = await makeRequest(`${API_BASE}/ai/suggestion-feedback`, {
      method: 'POST',
      body: JSON.stringify({
        userId: 'default_user',
        suggestionId: 'test_suggestion_1',
        suggestionType: 'auto_schedule',
        action: 'accept',
        rating: 5,
        feedbackText: '这个建议很有用，帮我合理安排了时间'
      })
    });

    if (feedbackResponse.status === 200) {
      console.log('   ✅ 建议反馈记录成功');
      console.log(`   💬 反馈动作: ${feedbackResponse.data.action}`);
      console.log(`   ⭐ 用户评分: ${feedbackResponse.data.rating}/5`);
    } else {
      console.log(`   ❌ 建议反馈记录失败: ${JSON.stringify(feedbackResponse.data)}`);
    }

    // 4. 再次测试个性化建议（验证学习效果）
    console.log('\n4️⃣ 再次测试个性化建议（验证学习效果）...');
    const improvedSuggestionsResponse = await makeRequest(`${API_BASE}/ai/personalized-suggestions`, {
      method: 'POST',
      body: JSON.stringify({
        userId: 'default_user',
        context: '用户需要时间管理方面的建议'
      })
    });

    if (improvedSuggestionsResponse.status === 200) {
      console.log('   ✅ 改进后的个性化建议生成成功');
      const improvedSuggestions = improvedSuggestionsResponse.data.suggestions || [];
      console.log(`   📈 建议数量: ${improvedSuggestions.length}`);
      
      const personalizedSuggestions = improvedSuggestions.filter(s => s.isPersonalized);
      console.log(`   🎯 高个性化建议数量: ${personalizedSuggestions.length}`);
      
      if (personalizedSuggestions.length > 0) {
        console.log('   🌟 最佳个性化建议:');
        const bestSuggestion = personalizedSuggestions[0];
        console.log(`      ${bestSuggestion.message}`);
        console.log(`      个性化评分: ${(bestSuggestion.personalizedScore * 100).toFixed(1)}%`);
      }
    } else {
      console.log(`   ❌ 改进后的建议生成失败: ${JSON.stringify(improvedSuggestionsResponse.data)}`);
    }

  } catch (error) {
    console.error('❌ 测试过程中出现错误:', error);
    console.error('错误详情:', error.message);
  }

  console.log('\n🎉 增强AI建议系统测试完成!');
  console.log('\n📋 功能总结:');
  console.log('✅ 用户行为追踪和分析');
  console.log('✅ 基于行为模式的个性化建议生成');
  console.log('✅ 建议反馈收集和学习');
  console.log('✅ 智能评分和建议排序');
  console.log('\n🚀 现在AI建议系统能够:');
  console.log('- 分析用户的工作习惯和偏好');
  console.log('- 基于历史行为提供个性化建议');
  console.log('- 学习用户反馈，持续改进建议质量');
  console.log('- 在合适的时间提供最相关的建议');
}

if (require.main === module) {
  testEnhancedAISuggestions().catch(console.error);
}

module.exports = { testEnhancedAISuggestions };
